﻿
using System.ComponentModel;
using System;
using Mbs;
namespace Mbs.Windows
{
    /// <summary>
    /// SmartPart Presenter 基类
    /// </summary>
    /// <typeparam name="TSmartPartView"></typeparam>
    public class SmartPartPresenter<TSmartPartView> : Presenter, IPresenter<TSmartPartView>,ISynchronizeInvoke 
        where TSmartPartView : ISmartPartView
    {
        public string ViewName { get; private set; }

        /// <summary>
        /// 受保护的构造函数
        /// </summary>
        /// <param name="viewName">SmartPart 视图名</param>
        protected SmartPartPresenter(string viewName)
        {
            ViewName = viewName;
        }

        private TSmartPartView GetSmartPartView(string smartPartViewId)
        {
            return this.BuildItem<TSmartPartView>(smartPartViewId);
        }

        private TSmartPartView view;
        /// <summary>
        /// 泛型视图
        /// </summary>
        /// <remarks>懒惰初始化视图</remarks>
        public new virtual TSmartPartView View
        {
            get
            {

                if (view != null)
                    return view;
                view = GetSmartPartView(ViewName);

                AttachView(view);
                return view;
            }
        }
        /// <summary>
        /// 显示SmartPart
        /// </summary>
        public virtual void ShowView()
        {
            if (View != null)
                View.ShowSmartPart();
        }


        #region ISynchronizeInvoke Members
        private ISynchronizeInvoke HWND
        {
            get
            {
                return SynchronizeService.SynchronizeObject;
            }
        }

        IAsyncResult ISynchronizeInvoke.BeginInvoke(Delegate method, object[] args)
        {
            if (HWND != null)
                return HWND.BeginInvoke(method, args);
            return null;
        }

        object ISynchronizeInvoke.EndInvoke(IAsyncResult result)
        {
            if (HWND != null)
                return HWND.EndInvoke(result);
            return null;
        }

        object ISynchronizeInvoke.Invoke(Delegate method, object[] args)
        {
            if (HWND != null)
                return HWND.Invoke(method, args);
            return null;
        }

        bool ISynchronizeInvoke.InvokeRequired
        {
            get { return HWND != null && HWND.InvokeRequired; }
        }

        #endregion
    }
}
